<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="员工姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入员工姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="服务区域" prop="serviceArea">
        <el-input v-model="queryParams.serviceArea" placeholder="请输入服务区域" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="擅长技能" prop="skills">
        <el-select v-model="queryParams.skills" placeholder="请选择擅长技能" multiple style="width: 100%">
          <el-option v-for="skill in skillList" :key="skill.value" :label="skill.label" :value="skill.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="平均评分" prop="avgRating">
        <el-input v-model="queryParams.avgRating" placeholder="请输入平均评分" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input-number v-model="queryParams.age" placeholder="请输入年龄" style="width: 100%;" />
      </el-form-item>
      <el-form-item label="性别" prop="gender">
        <el-select v-model="queryParams.gender" placeholder="请选择性别" clearable>
          <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="手机号码" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入员工手机号码" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="工作经验" prop="experience">
        <el-input v-model="queryParams.experience" placeholder="请输入工作经验" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="员工状态" prop="employmentStatus">
        <el-select v-model="queryParams.employmentStatus" placeholder="请选择员工状态" clearable>
          <el-option v-for="dict in dict.type.employee_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['user:employee:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['user:employee:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['user:employee:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['user:employee:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 卡片式布局 -->
    <el-row :gutter="20">
      <el-col :span="6" v-for="employee in employeeList" :key="employee.id" style="margin-bottom: 20px;">
        <el-card shadow="hover" class="employee-card">
          <div slot="header" class="clearfix">
            <img v-if="employee.avatar" :src="employee.avatar"
              style="width: 30px; height: 30px; border-radius: 50%; vertical-align: middle; margin-right: 10px;" />
            <span>{{ employee.name }}</span>
            <el-tag :type="employee.employmentStatus === 1 ? 'success' : 'danger'" size="mini" style="float: right;">
              {{ employee.employmentStatus === 1 ? '接单中' : '空闲' }}
            </el-tag>
          </div>

          <div class="card-content">
            <div class="info-section">
              <div class="info-item">
                <span class="info-label">性别：</span>
                <dict-tag :options="dict.type.sys_user_sex" :value="employee.gender" />
              </div>
              <div class="info-item">
                <span class="info-label">年龄：</span>
                <span>{{ employee.age }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">电话：</span>
                <span>{{ employee.phone }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">评分：</span>
                <el-rate v-model="employee.avgRating" disabled show-score text-color="#ff9900" score-template="{value}">
                </el-rate>
              </div>
            </div>

            <div class="skills-section">
              <h4>擅长技能</h4>
              <div class="skill-tags">
                <template v-if="employee.skillList && employee.skillList.length > 0">
                  <el-tag v-for="skill in employee.skillList" :key="skill.id" size="small"
                    style="margin-right: 5px; margin-bottom: 5px;">
                    {{ skill.name }}
                  </el-tag>
                </template>
                <span v-else>暂无技能</span>
              </div>
            </div>

            <div class="intro-section">
              <h4>个人简介</h4>
              <p class="intro-text">{{ employee.intro || '暂无简介' }}</p>
            </div>

            <div class="action-buttons">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(employee)"
                v-hasPermi="['user:employee:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(employee)"
                v-hasPermi="['user:employee:remove']">删除</el-button>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-button @click="toggleAllFields" size="mini" type="warning" style="margin-bottom: 10px;">全部切换</el-button>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="员工姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入员工姓名" :disabled="nameDisabled">
            <template v-if="nameDisabled" #append>
              <el-button @click="nameDisabled = false" icon="el-icon-unlock" circle size="mini" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="身份证" prop="idCard">
          <el-input v-model="form.idCard" placeholder="请输入身份证" :disabled="idCardDisabled" maxlength="18">
            <template v-if="idCardDisabled" #append>
              <el-button @click="idCardDisabled = false" icon="el-icon-unlock" circle size="mini" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="擅长技能" prop="skills">
          <el-select v-model="form.skills" placeholder="请选择擅长技能" multiple style="width: 100%" :disabled="skillsDisabled">
            <template v-if="skillsDisabled" #suffix>
              <el-button @click.stop="skillsDisabled = false" icon="el-icon-unlock" circle size="mini" style="margin-left: 4px;" />
            </template>
            <el-option v-for="skill in skillList" :key="skill.value" :label="skill.label" :value="skill.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务区域" prop="serviceArea">
          <el-input v-model="form.serviceArea" placeholder="请选择服务区域" :readonly="true" :disabled="serviceAreaDisabled">
            <template #append>
              <el-button @click="showMapDialog = true" :disabled="serviceAreaDisabled">地图选址</el-button>
              <el-button v-if="serviceAreaDisabled" @click.stop="serviceAreaDisabled = false" icon="el-icon-unlock" circle size="mini" style="margin-left: 4px;" />
            </template>
          </el-input>
          <MapSelector :modelValue="showMapDialog" @update:modelValue="showMapDialog = $event" @select="handleMapSelect" />
        </el-form-item>
        <el-form-item label="员工状态" prop="employmentStatus">
          <el-select v-model="form.employmentStatus" placeholder="请选择员工状态" :disabled="employmentStatusDisabled">
            <template v-if="employmentStatusDisabled" #suffix>
              <el-button @click.stop="employmentStatusDisabled = false" icon="el-icon-unlock" circle size="mini" style="margin-left: 4px;" />
            </template>
            <el-option v-for="dict in dict.type.employee_status" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="平均评分" prop="avgRating">
          <el-input v-model="form.avgRating" placeholder="请输入平均评分" :disabled="avgRatingDisabled">
            <template v-if="avgRatingDisabled" #append>
              <el-button @click="avgRatingDisabled = false" icon="el-icon-unlock" circle size="mini" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input-number v-model="form.age" :min="20" :max="60" :disabled="ageDisabled" placeholder="请输入年龄" style="width: 100%">
            <template v-if="ageDisabled" #append>
              <el-button @click="ageDisabled = false" icon="el-icon-unlock" circle size="mini" />
            </template>
          </el-input-number>
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择性别" :disabled="genderDisabled">
            <template v-if="genderDisabled" #suffix>
              <el-button @click.stop="genderDisabled = false" icon="el-icon-unlock" circle size="mini" style="margin-left: 4px;" />
            </template>
            <el-option v-for="dict in dict.type.sys_user_sex" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入员工手机号码" :disabled="phoneDisabled">
            <template v-if="phoneDisabled" #append>
              <el-button @click="phoneDisabled = false" icon="el-icon-unlock" circle size="mini" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="工作经验" prop="experience">
          <el-input v-model="form.experience" placeholder="请输入工作经验" :disabled="experienceDisabled">
            <template v-if="experienceDisabled" #append>
              <el-button @click="experienceDisabled = false" icon="el-icon-unlock" circle size="mini" />
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="个人简介" prop="intro">
          <el-input v-model="form.intro" type="textarea" placeholder="请输入个人简介" :disabled="introDisabled">
            <template v-if="introDisabled" #append>
              <el-button @click="introDisabled = false" icon="el-icon-unlock" circle size="mini" />
            </template>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeList, getEmployeeWithSkills } from "@/api/user/employeeskill"
import { delEmployee, addEmployee, updateEmployee } from "@/api/user/employee"

//1. 获取员工编号对应的员工技能
import { listSkill } from "@/api/user/skill"
import MapSelector from '@/components/MapSelector/index.vue';

export default {
  name: "Employee",
  dicts: ['employeeskill', 'employee_status', 'sys_user_sex'],
  components: {
    MapSelector
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 服务人员表格数据
      employeeList: [],
      // 获取员工技能
      skillList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 地图选址弹窗
      showMapDialog: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        skills: [],
        serviceArea: null,
        avgRating: null,
        age: null,
        gender: null,
        phone: null,
        experience: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "员工姓名不能为空", trigger: "blur" }
        ],
        idCard: [
          { required: true, message: "身份证不能为空", trigger: "blur" },
          { min: 18, max: 18, message: "身份证必须为18位", trigger: "blur" },
          { pattern: /^[1-9]\d{16}[\dXx]$/, message: "身份证格式不正确", trigger: "blur" }
        ],
        age: [
          { required: true, message: "年龄不能为空", trigger: "blur" },
          { type: 'number', min: 20, max: 60, message: "年龄必须在20-60之间", trigger: "blur" }
        ],
        gender: [
          { required: true, message: "请选择性别", trigger: "change" },
          { validator: (rule, value, callback) => {
              if (value === 0 || value === 1 || value === '男' || value === '女') {
                callback();
              } else {
                callback(new Error("性别只能为男或女"));
              }
            }, trigger: "change"
          }
        ],
        phone: [
          { required: true, message: "员工手机号码不能为空", trigger: "blur" },
          { pattern: /^1[3-9]\d{9}$/, message: "请输入11位有效手机号", trigger: "blur" }
        ],
      },
      // 是否添加模式
      isAddMode: false,
      // 字段禁用控制
      nameDisabled: false,
      idCardDisabled: false,
      ageDisabled: false,
      genderDisabled: false,
      phoneDisabled: false,
      experienceDisabled: false,
      introDisabled: false,
      skillsDisabled: false,
      serviceAreaDisabled: false,
      employmentStatusDisabled: false,
      avgRatingDisabled: false,
    }
  },
  created() {
    this.getList();
    this.fetchSkills(); // 初始化时获取技能列表
  },
  methods: {
    /** 查询服务人员列表 */
    getList() {
      this.loading = true

      // 保存原始skills数组
      const originalSkills = this.queryParams.skills;

      // 临时转换为字符串格式用于查询
      const queryParams = {
        ...this.queryParams,
        skills: originalSkills && originalSkills.length ? originalSkills.join(",") : null
      };

      console.log(JSON.stringify(this.queryParams))

      getEmployeeList(queryParams).then(response => {
        this.employeeList = response.rows;
        this.total = response.total;

        // 恢复skills为数组格式
        this.queryParams.skills = originalSkills;

        this.loading = false;
      }).catch(() => {
        // 出错时也要恢复skills
        this.queryParams.skills = originalSkills;
        this.loading = false;
      });
    },
    fetchSkills() {
      listSkill().then((response) => {
        this.skillList = response.rows.map(item => ({
          value: item.id.toString(),
          label: item.name
        }))
      });
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        idCard: null,
        skills: null,
        serviceArea: null,
        employmentStatus: null,
        healthCert: null,
        avgRating: null,
        age: null,
        gender: null,
        phone: null,
        experience: null,
        intro: null,
        serviceCount: null,
        createTime: null,
        avatar: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.queryParams.age = null
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.isAddMode = true
      this.open = true
      this.title = "添加服务人员"
      // 全部解锁
      Object.keys(this.form).forEach(field => {
        if (this.hasOwnProperty(`${field}Disabled`)) {
          this[`${field}Disabled`] = false;
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.isAddMode = false
      const id = row.id || this.ids
      getEmployeeWithSkills(id).then(response => {
        this.form = response.data;
        this.form.skills = response.data.skillList.map(skill => skill.id);
        this.open = true
        this.title = "修改服务人员"
        // 初始化时强制校验并设置禁用状态
        this.$nextTick(() => {
          Object.keys(this.form).forEach(field => {
            if (this.hasOwnProperty(`${field}Disabled`) && this.$refs.form) {
              this.$refs.form.validateField(field, valid => {
                this[`${field}Disabled`] = valid === '';
              });
            }
          });
        });
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const formData = {
            ...this.form,
            skills: this.form.skills?.join(",") || null // 数组转字符串
          };

          const operation = this.form.id ?
            updateEmployee(formData) :
            addEmployee(formData);

          operation.then(response => {
            this.$modal.msgSuccess(this.form.id ? "修改成功" : "新增成功");
            this.open = false;
            this.getList();
          });
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除服务人员编号为"' + ids + '"的数据项？').then(function () {
        return delEmployee(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => { })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('user/employee/export', {
        ...this.queryParams
      }, `employee_${new Date().getTime()}.xlsx`)
    },
    handleMapSelect({ address, longitude, latitude }) {
      this.form.serviceArea = address;
      // 如需存经纬度可扩展
      this.showMapDialog = false;
    },
    toggleAllFields() {
      this.nameDisabled = !this.nameDisabled;
      this.idCardDisabled = !this.idCardDisabled;
      this.ageDisabled = !this.ageDisabled;
      this.genderDisabled = !this.genderDisabled;
      this.phoneDisabled = !this.phoneDisabled;
      this.experienceDisabled = !this.experienceDisabled;
      this.introDisabled = !this.introDisabled;
      this.skillsDisabled = !this.skillsDisabled;
      this.serviceAreaDisabled = !this.serviceAreaDisabled;
      this.employmentStatusDisabled = !this.employmentStatusDisabled;
      this.avgRatingDisabled = !this.avgRatingDisabled;
    },
    _autoLockField(field, val) {
      if (!this.isAddMode) {
        // 只要当前字段未禁用，内容变化都要校验，校验通过就禁用
        if (!this[`${field}Disabled`]) {
          this.$refs.form.validateField(field, valid => {
            if (valid === '') {
              this[`${field}Disabled`] = true;
            }
          });
        }
      } else {
        this[`${field}Disabled`] = false;
      }
    },
  },
  watch: {
    'form.name'(val) { this._autoLockField('name', val); },
    'form.idCard'(val) { this._autoLockField('idCard', val); },
    'form.age'(val) { this._autoLockField('age', val); },
    'form.gender'(val) { this._autoLockField('gender', val); },
    'form.phone'(val) { this._autoLockField('phone', val); },
    'form.experience'(val) { this._autoLockField('experience', val); },
    'form.intro'(val) { this._autoLockField('intro', val); },
    'form.skills'(val) { this._autoLockField('skills', val); },
    'form.serviceArea'(val) { this._autoLockField('serviceArea', val); },
    'form.employmentStatus'(val) { this._autoLockField('employmentStatus', val); },
    'form.avgRating'(val) { this._autoLockField('avgRating', val); },
  },
}
</script>

<style scoped>
.employee-card {
  height: 100%;
  transition: all 0.3s;
  margin-bottom: 20px;
}

.employee-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

.card-content {
  padding: 10px;
}

.info-section {
  margin-bottom: 15px;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.info-label {
  width: 60px;
  color: #909399;
  font-size: 13px;
}

.skills-section,
.intro-section {
  margin-bottom: 15px;
}

.skills-section h4,
.intro-section h4 {
  font-size: 14px;
  margin-bottom: 8px;
  color: #303133;
}

.skill-tags {
  display: flex;
  flex-wrap: wrap;
}

.intro-text {
  color: #606266;
  line-height: 1.5;
  font-size: 13px;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #f0f0f0;
  padding-top: 10px;
  margin-top: 10px;
}

.el-rate {
  display: inline-block;
}
</style>
